<?php

class Categories extends Controller {

	function Categories()
	{
		parent::Controller();	
        if(!admin_session_check()) redirect('admin/login');
        if(!is_allowed("all")) show_404();
        $this->load->model('productsmodel');       
	}     
    
    function index()
    {

        $data["list"] = $this->productsmodel->admin_get_all_categories();
        $data["response"] = get_response();        

        $this->load->view('admin/default/head');  
        $this->load->view('admin/default/header', array('selected'=>'products'));  
        $this->load->view("admin/default/nav_products", array('selected' => 'categories'));
        $this->load->view("admin/default/quick_search");
        $this->load->view('admin/categories/cat_list', $data);   
        $this->load->view('admin/default/footer');   

    }
    function edit($id = NULL, $standalone = FALSE)
    {
        if($id == NULL) show_404();

        $data["item"] = $this->productsmodel->admin_get_category($id); 
        if(empty($data["item"])) show_404();

        $data["children"] = $this->productsmodel->admin_get_cat_children($id);
        $data["list"] = $this->productsmodel->admin_get_parent_categories($id);
        
        $this->_process_form();

        $data["action"] = "update";                                            
        $data["token"] = generate_token("categories",720);
        $data["standalone"] = $standalone;

        $this->load->view('admin/default/head'); 
        if ($standalone == false){   
            $this->load->view('admin/default/header', array('selected'=>'products'));  
            $this->load->view("admin/default/nav_products", array('selected' => 'categories'));
        }
        $this->load->view('admin/categories/cat_form', $data);   
        if ($standalone == false){  
            $this->load->view('admin/default/footer');   
        }

    }
    function add($standalone = FALSE)
    {
        $this->_process_form();

        $data["item"] = array(
                "id_Categories" => "",
                "Parent_Categories" => "", 
                "Title_Categories" => "", 
                "Introduction_Categories" => "",
                "Description_Categories" => "",
                "Image_Categories" => ""
        ); 

        $data["children"] = array();
        $data["list"] = $this->productsmodel->admin_get_parent_categories();

        $data["action"] = "create";
        $data["token"] = generate_token("categories",720);
        $data["standalone"] = $standalone;

        $this->load->view('admin/default/head');  
        if ($standalone == false){  
            $this->load->view('admin/default/header', array('selected'=>'products'));  
            $this->load->view("admin/default/nav_products", array('selected' => 'categories'));
        }
        $this->load->view('admin/categories/cat_form', $data);   
        if ($standalone == false){  
            $this->load->view('admin/default/footer');   
        }

    } 

    function deactivate($id = false){

        if($id == NULL) show_404();  
        $data = array('Active_Categories' => 0);
        $this->productsmodel->admin_update_category($id, $data);
        $item = $this->productsmodel->admin_get_category($id);

        $subitems = $this->productsmodel->admin_get_cat_children($id);
        if(!empty($subitems)){ //deativate children categories
            foreach($subitems as $subitem){
                $data = array('Active_Categories' => 0);
                $this->productsmodel->admin_update_category($subitem['id_Categories'], $data);
            }
            $extra = '<br />Warning: All '.count($subitems).' subcategories of <i>'.$item["Title_Categories"].'</i> were deactivated too.';
        } else $extra ="";

        set_response('success', "The category <i>".$item["Title_Categories"].'</i> is now inactive. <a href="'.site_url("admin/categories/preview/".$item["id_Categories"]).'" rel="view">Click to view</a>'.$extra);
        redirect('admin/categories');
    }
    function activate($id = false){

        if($id == NULL) show_404();  
        $data = array('Active_Categories' => 1);
        $this->productsmodel->admin_update_category($id, $data);
        $item = $this->productsmodel->admin_get_category($id);

        $subitems = $this->productsmodel->admin_get_cat_children($id);
        if(!empty($subitems)) $extra = '<br />Warning: There are '.count($subitems).' subcategories of <i>'.$item["Title_Categories"].'</i> still inactive.';
        else $extra ="";

        set_response('success', "The category <i>".$item["Title_Categories"].'</i> is now active. <a href="'.site_url("admin/categories/preview/".$item["id_Categories"]).'" rel="view">Click to view</a>'.$extra);
        redirect('admin/categories');
    }
    function remove($id = false){

        if($id == NULL) show_404();  

        $data["item"] = $this->productsmodel->admin_get_category($id);
        $data["subitems"] = $this->productsmodel->admin_get_cat_children($data["item"]["id_Categories"], "id_Categories AS id, Title_Categories AS title, Introduction_Categories AS intro, Image_Categories AS image, Active_Categories AS active");
        if (empty($data["subitems"])) $data["subitems"] = $this->productsmodel->admin_get_products_by_cat($data["item"]["id_Categories"], "id_Products AS id, Name_Products AS title, Introduction_Products AS intro, Main_Image AS image, Approved_Products AS approved, Active_Products AS active");;

        if(empty($data["item"])){

            set_response('error', "The category you're attempting to delete does not exist");
            redirect('admin/categories');

        } else {

            $data["controller"] = "admin/categories";
            $this->load->model('glossarymodel');

            $this->load->view('admin/default/head');          
            $this->load->view('admin/default/header', array('selected'=>'products'));  
            $this->load->view("admin/default/nav_products", array('selected' => 'categories'));  
            $this->load->view('admin/categories/cat_delete', $data);   
            $this->load->view('admin/default/footer');   

        }
    } 
    function confirm_removal($id = false){

        if($id == NULL) show_404();  

        $data["item"] = $this->productsmodel->admin_get_category($id);
        $data["subitems"] = $this->productsmodel->admin_get_cat_children($data["item"]["id_Categories"], "id_Categories AS id, Title_Categories AS title, Introduction_Categories AS intro, Image_Categories AS image, Active_Categories AS active");
        if (empty($data["subitems"])) $data["subitems"] = $this->productsmodel->admin_get_products_by_cat($data["item"]["id_Categories"], "id_Products AS id, Name_Products AS title, Introduction_Products AS intro, Main_Image AS image, Approved_Products AS approved, Active_Products AS active");;


        if(empty($data["item"])){

            set_response('error', "The category you're attempting to delete does not exist");
            redirect('admin/categories');

        } else if (!empty($data["subitems"])) {                                                      

            redirect('admin/categories/remove/'.$id, 'refresh');

        } else {

            $this->productsmodel->admin_delete_category($id);
            set_response('success', "The products category <i>".$data["item"]["Title_Categories"]."</i> was deleted.");
            redirect('admin/categories');
        }
    }

    function preview($id = NULL)
    {
        if($this->input->post("submit_action") === FALSE){

            $data["item"] = $this->productsmodel->admin_get_category($id); 
            if (empty($data["item"])) show_404();             
            $data["action"] = "view";

        } else {

            $data["item"] = array(
                'id_Categories' => $this->input->post("id", TRUE),
                'parent_Categories' => $this->input->post("parent", TRUE),  
                'Title_Categories' => ucfirst($this->input->post("title", TRUE)),
                'Introduction_Categories' => $this->input->post("introduction", TRUE),
                'Description_Categories' => $this->input->post("description", TRUE),
                'Image_Categories' => $this->input->post("image", TRUE));

            $data["action"] = "preview";

        }

        $data["subitems"] = $this->productsmodel->get_categories_by_parent($data["item"]["id_Categories"], "categories.id_Categories AS id, Title_Categories AS title, Introduction_Categories AS intro, Image_Categories AS image, Active_Categories AS active");
        if (empty($data["subitems"])) $data["subitems"] = $this->productsmodel->get_products_by_category($data["item"]["id_Categories"], "id_Products AS id, Name_Products AS title, Introduction_Products AS intro, Main_Image AS image, Approved_Products AS approved, Active_Products AS active");;

        $data["controller"] = "categories";
        $this->load->model('glossarymodel');
        $this->load->view('admin/previews/preview_category_template', $data);   

    }

    private function _process_form()
    {        
        $this->load->library("form_validation");
        
        if($this->input->post("submit_action") !== FALSE){

            if ($this->_validate_form()) {
                
                if (validate_token("categories",$this->input->post("token",TRUE))){

                    $data = array(
                        'id_Categories' => $this->input->post("id"),
                        'Title_Categories' => $this->input->post("title"),  
                        'Introduction_Categories' => $this->input->post("introduction"),
                        'Description_Categories' => $this->input->post("description"),
                        'Image_Categories' => $this->input->post("image"), 
                        'Parent_Categories' => ($this->input->post("parent")=="") ? NULL : $this->input->post("parent")
                    );

                    $standalone = $this->input->post("standalone");

                    switch($this->input->post("submit_action")){    

                        case 'create':

                            $new_id = $this->productsmodel->admin_insert_category($data);

                            if ($standalone == false){ 
                                set_response('success','The category <i>'.$data['Title_Categories'].'</i> was created. <a href="'.site_url("admin/categories/edit/".$new_id).'">Click to edit</a>');
                                redirect("admin/categories");
                            } else {
                                $this->_standalone_success($new_id);
                            }
                            
                            set_response('success','The category <i>'.$data['Title_Categories'].'</i> was created. <a href="'.site_url("admin/categories/preview/".$new_id).'" rel="view">Click to view</a>');

                        break;
                        case 'update':

                            $this->productsmodel->admin_update_category($this->input->post("id"), $data);

                            if ($standalone == false){ 
                                set_response('success','The category <i>'.$data['Title_Categories'].'</i> was updated. <a href="'.site_url("admin/categories/preview/".$this->input->post("id")).'" rel="view">Click to view</a>');
                                redirect("admin/categories");
                            } else {
                                $this->_standalone_success($this->input->post("id"));
                            }

                        break;        

                    }

                }
            }   
        }
        
    }

    private function _validate_form(){
        
        $config = array( 
                        array(
                         'field'   => 'title',
                         'label'   => 'Title',
                         'rules'   => 'trim|required|xss_clean|callback_check_duplicated|max_length[250]'
                        ),
                        array(
                         'field'   => 'introduction',
                         'label'   => 'Introduction',
                         'rules'   => 'trim|required|xss_clean'
                        ),
                        array(
                         'field'   => 'description',
                         'label'   => 'Description',
                         'rules'   => 'trim|xss_clean'
                        ),             
                        array(
                         'field'   => 'image',
                         'label'   => 'Image',
                         'rules'   => 'trim|required|xss_clean'
                        ),             
                        array(
                         'field'   => 'parent',
                         'label'   => 'Parent',
                         'rules'   => 'trim|xss_clean'
                        )
                    );
        
                                                 
        $this->form_validation->set_rules($config);       
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        
        if ($this->form_validation->run($this) == FALSE){
            return FALSE;
        }else
            return TRUE;

    }

     public function check_duplicated($name){ 

        $id = $this->input->post("id");

        if($this->productsmodel->is_duplicated('categories','Title_Categories',$name,'id_Categories',$id)){
            $this->form_validation->set_message('check_duplicated', "A category with that name already exists");
            return FALSE;
        }else{
            return TRUE;    
        }
    }

    private function _standalone_success($id=false){
               
        $this->load->view('admin/default/head');          
        $this->load->view('admin/categories/cat_standalone_success', array("id" => $id));
                 
    } 
    // returns the list in json format for the admin select box
    public function get_json_list()
    {
        $list = $this->productsmodel->admin_get_json_categories();
        echo json_encode($list);
        return;
    }
    //returns partial view of a single item. Fit to be used in ajax calls.
    public function view()
    {
        $this->load->library("form_validation");
        if ($this->input->post("id") === false) return;
        else $id = $this->input->post("id");

        $item = $this->productsmodel->admin_get_category($id);
        $this->load->model('glossarymodel');
        $this->load->view('admin/previews/category_item_detail', array("item" => $item));
        return;
    } 

}

/* End of file welcome.php */
/* Location: ./system/application/controllers/welcome.php */